package com.itheima.controller;

import com.itheima.common.Result;
import com.itheima.common.utils.JwtUtils;
import com.itheima.pojo.Emp;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Objects;

/**
 * LoginController
 *
 * @author liliudong
 * @version 1.0
 * @description 登录控制器
 * @date 2023/7/16 17:04
 */
@RestController
@Slf4j
public class LoginController {

    @Autowired
    private EmpService empService;

    /**
     * 登录
     *
     * @param emp
     * @return
     */
    @PostMapping("/login")
    public Result<?> login(@RequestBody Emp emp) {
        // 用账号 + 密码去数据库查，只要能查到用户
        Emp empExist = empService.login(emp.getUsername(), emp.getPassword());
        if (Objects.isNull(empExist)) {
            return Result.error("登录失败！");
        }
        // 生成
        HashMap<String, Object> params = new HashMap<>(8);
        params.put("userId", empExist.getId());

        String jwt = JwtUtils.generateJwt(params);
        return Result.success(jwt);
    }
}
